// pages/SavePost/SavePost.js
var util = require('../../utils/util.js')
var app = getApp()
var rootUrl = app.globalData.rootDocment
var imgPublicUrl = rootUrl + 'Public/Home/images/'
var valNum = 0 
Page({ 

  /**
   * 页面的初始数据
   */
  data: {
    savePostAddressButton:true,
    savePostAddressMain:false,
	  receivadrtp: true,	//	是否默认开启请求收货地址
	  receivadrID: null,	//	收货地址ID
	  receivname:null,	//	收货人姓名
	  receivphone:null,	//	收货人电话
	  receivaddress:null,	//	收货详细地址
    classoneid: 0,	//	一级分类ID
    classtwoid: 0,	//	二级分类ID
    postNumber: 1,	//默认初始袋数
	  couponid: null,	//优惠券id
	  couponamount: 0,	//优惠金额
	  couponstatus:false, //优惠券是否显示
    unitprice: 0,  //单价
	  aggregateamount: 0,  //累计金额
	  totalamount: 0,  //订单总金额
	  remarks:"", //订单备注
    submitst: true, //提交状态
    submitcs: 0, //提交次数
	  imageArr: {
		  addressIcon: imgPublicUrl + 'addressIcon.png',
		  SavePostHeaderImg: imgPublicUrl + 'SavePostHeaderImg.jpg',
		  minusIcon: imgPublicUrl + 'minusIcon.png',
		  addIcon: imgPublicUrl + 'addIcon.png',
		  rightIcon: imgPublicUrl + 'rightIcon.png'
	  },
    //大件取货数据
    selectPicker:true,
    multirow: [],
    multiIndex: [0, 0],
    multiArray: [[{ id: "0", name: "请选择" }], []],
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
	  app.publicchangenavigate()
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
	  var that = this
	  if (that.data.receivadrtp){
		  //判断用户是否有默认收货地址
		  util.AJAX('Home/Index/checkreceivadr', { userinfoid: app.globalData.userInfoId, userphone: app.globalData.userPhone }, function (res) { //方法体
			  if (res.data.StatusCode == 100) {  //成功
				  that.setData({
					  savePostAddressButton: false,
					  savePostAddressMain: true,
					  receivadrID: res.data.Info.id,
					  receivname: res.data.Info.name,	//	收货人姓名
					  receivphone: res.data.Info.tel,	//	收货人电话
					  receivaddress: res.data.Info.provinces + res.data.Info.city + res.data.Info.area + res.data.Info.detailadrs	//	收货详细地址
				  })
			  }else{
          that.setData({
					  savePostAddressButton: true,
					  savePostAddressMain: false,
            receivadrID: null,	//	收货地址ID
				  })
        }
		  }, 'POST')
	  }

    //获取分类
    util.AJAX('Home/Index/getDJClass', {}, function (res) { //方法体
      if (res.data.StatusCode == 100) {  //成功
        var onerow = res.data.Info.one
        var tworow = res.data.Info.two
        var morenone = { id: "0", name: "请选择" }
        onerow.unshift(morenone)
        if (that.data.multiArray[1][0]){

        }else{
          that.setData({
            multiArray: [onerow, []],
            multirow: tworow, //第二列
          })
        }
      }
    }, 'POST')

	  //默认计算
    that.setData({
      aggregateamount: util.mul(parseInt(that.data.postNumber),parseFloat(that.data.unitprice)),  //累计金额
      totalamount: util.sub(util.mul(parseInt(that.data.postNumber),parseFloat(that.data.unitprice)),parseFloat(that.data.couponamount)),  //订单总金额
	  })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
	  return app.globalshare();
  },
  //洗衣件数
  numTap:function(e){
    var id = e.currentTarget.id;
    var num = this.data.postNumber;

    //干掉优惠券信息
    this.setData({
      couponid: null,	//优惠券id
      couponamount: 0,	//优惠金额
      couponstatus: false, //优惠券是否显示
    })

    if (id == '1') {
      if (num == 1) {
        this.setData({
          postNumber: num
        })
      } else {
        this.setData({
          postNumber: num - 1
        })
      }
    } else {
      this.setData({
        postNumber: num + 1
      })
    }
    //默认计算
    this.setData({
      aggregateamount: util.mul(parseInt(this.data.postNumber), parseFloat(this.data.unitprice)),  //累计金额
      totalamount: util.sub(util.mul(parseInt(this.data.postNumber), parseFloat(this.data.unitprice)), parseFloat(this.data.couponamount)),  //订单总金额
    })
      
  },
  // 确认提交
  savePostSuccessTap:function(){
	 var that = this
   var ystimes = util.functionrd(10, 1500);
   //是否有收货地址
   if (that.data.receivadrID){
     //判断分类
     if(that.data.classoneid > 0 && that.data.classtwoid > 0){
       that.setData({
         submitst: true, //提交状态
       })
     }else{
       that.setData({
         submitst: false, //提交状态
       })
       wx.showModal({
         title: '提示',
         showCancel: false,
         content: '请选择分类'
       })
     }
   }else{
     that.setData({
       submitst: false, //提交状态
     })
     wx.showModal({
       title: '提示',
       showCancel: false,
       content: '请选择收货地址'
     })
   }

   if (that.data.submitst && that.data.submitcs === 0){
     //开启加载
     wx.showLoading({
       title: '加载中',
       mask:true,
     })

     that.setData({
       submitst: false, //提交状态
     })
     
      var dats = {
        userinfoid: app.globalData.userInfoId, //用户ID
        ordertotalnum: that.data.postNumber,	//订单总件数
        amountpayable: that.data.aggregateamount,	//应付金额
        amountrealpay: that.data.totalamount,	//实付金额
        cabinetid: that.data.classoneid, //智能柜ID
        cabinetdoorid: that.data.classtwoid, //智能柜门ID
        addressid: that.data.receivadrID, //配送地址ID
        discountid: that.data.couponid, //优惠券ID
        ramark: that.data.remarks, //订单备注
      }

      //延时请求
      setTimeout(function () {
          //判断用户是否有默认收货地址
          util.AJAX('Home/Index/saveorderdatabig', dats, function (res) { //方法体
            //关闭加载
            wx.hideLoading()
            that.setData({ submitcs: 1 })
            if (res.data.StatusCode == 100) {  //下单成功
              var Info = res.data.Info
              wx.showToast({
                title: '订单创建成功',
                icon: 'success',
                duration: 2000,
                success: function (res) {
                  setTimeout(function () {
                    wx.redirectTo({
                      url: '/pages/bigpay/bigpay?ordernum=' + Info
                    })
                  }, 2000)
                }
              })
            } else {
              that.setData({
                submitcs: 0,
                submitst: true, //提交状态
              })
              wx.showModal({
                title: '提示',
                showCancel: false,
                content: res.data.Msg
              })
            }
          }, 'POST')
      }, ystimes)
    }
  },
  //收货地址操作
  addAddressButtonlist:function(){
    if (app.checkLogin()) {
      app.publicnavigateTologing('/pages/address_list/address_list?tps=ap')
    } else {
      app.navigateTologing() //跳转到登录
    }
  },
  //收货地址添加操作
  addAddressButton: function () {
    if (app.checkLogin()) {
      app.publicnavigateTologing('/pages/address/address?tps=bp')
    } else {
      app.navigateTologing() //跳转到登录
    }
  },
	//选择优惠券
	selectcoupon : function () {
    if (app.checkLogin()) {
      app.publicnavigateTologing('/pages/SavePost/selectCoupon/selectCoupon?totalmoney=' + this.data.aggregateamount)
    } else {
      app.navigateTologing() //跳转到登录
    }
	},
  bindMultiPickerChange: function (e) {
    this.setData({
      multiIndex: e.detail.value
    })
  },
  bindMultiPickerColumnChange: function (e) {
    var that = this
    var data = {
      classoneid: that.data.classoneid,	//	一级分类ID
      classtwoid: that.data.classtwoid,	//	二级分类ID
      unitprice: that.data.unitprice,  //单价
      selectPicker: that.data.selectPicker,
      multiArray: that.data.multiArray,
      multiIndex: that.data.multiIndex,
      aggregateamount: 0,  //累计金额
      totalamount: 0,  //订单总金额
    };
    data.multiIndex[e.detail.column] = e.detail.value
    switch (e.detail.column) {
      case 0:
        switch (data.multiIndex[0]) {
          case 0:
            data.multiArray[1] = []
            data.unitprice = 0
            break;
          default:
            var idx = data.multiIndex[0] - 1
            data.multiArray[1] = that.data.multirow[idx]
            data.unitprice = that.data.multirow[idx][0]['cktprice']
        }
        data.multiIndex[1] = 0
        break;
    }

    data.classoneid = data.multiArray[0][data.multiIndex[0]]['id']

    if (data.multiArray[1].length > 0){
      data.selectPicker = false
      data.classtwoid = data.multiArray[1][data.multiIndex[1]]['id']
      data.unitprice = data.multiArray[1][data.multiIndex[1]]['cktprice']
    }else{
      data.selectPicker = true
      data.classtwoid = 0
    }
    //计算金额
    data.aggregateamount = util.mul(parseInt(that.data.postNumber), parseFloat(data.unitprice))
    data.totalamount = util.sub(util.mul(parseInt(that.data.postNumber), parseFloat(data.unitprice)), parseFloat(that.data.couponamount))
    //计算金额
    that.setData(data)
  },
})